//
//  DSFUserInfo.m
//  TVFan3.0
//
//  Created by suma on 14-9-16.
//  Copyright (c) 2014年 李胜男. All rights reserved.
//
//用户信息单例
#import "DSFUserInfo.h"

@implementation DSFUserInfo
static DSFUserInfo * shareUserInfo=nil;

+(DSFUserInfo *)shareUserInstance
{
    @synchronized(self)
	{
		if (!shareUserInfo){
			shareUserInfo = [[DSFUserInfo alloc] init];
		}
	}
	
	return shareUserInfo;
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+ (NSURLSessionDataTask *)userLogin:(void (^)(BOOL result,NSError *error))block withUsername:(NSString *)username andPassword:(NSString *)password andUserType:(int)userType andPushUserId:(NSString *)pushUserId andImei:(NSString *)imei{
    NSDictionary * dict = @{@"username": username, @"password":password,@"userType":@(userType),@"imei":imei,@"deviceType":@(2)};
    NSMutableDictionary * temp = [[NSMutableDictionary alloc] initWithDictionary:dict];
    if (pushUserId) {
        [temp setObject:pushUserId forKey:@"pushId"];
    }
    [DSFUserInfo shareUserInstance].isLogin = NO;
    return [[AFAppDotNetAPIClient httpSharedClient] POST:@"user/login" parameters:temp success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSLog(@"%@",task.originalRequest);
        NSDictionary *response = [JSON valueForKeyPath:@"data"];
        long code = [[JSON valueForKeyPath:@"code"] integerValue];
        BOOL result;
        if (code == 10000) {
            result = YES;
            shareUserInfo.token = [response valueForKeyPath:@"token"];
            shareUserInfo.userId = [[response valueForKeyPath:@"id"] integerValue];
            shareUserInfo.phone = [response valueForKeyPath:@"phone"];
            shareUserInfo.sex = [[response valueForKeyPath:@"sex"] integerValue];
            shareUserInfo.icon = [response valueForKeyPath:@"icon"];
            shareUserInfo.last_login_time = [response valueForKeyPath:@"last_login_time"];
            NSArray *arrary = [response valueForKeyPath:@"clazz_users"];
            shareUserInfo.clazz_user = [[ClassUserMoedel alloc] initWithDictionary:[arrary objectAtIndex:0]  error:nil];
            shareUserInfo.clazz_user.clazz = [[ClassModel alloc] initWithDictionary:[[arrary objectAtIndex:0] valueForKeyPath:@"clazz"] error:nil];
            shareUserInfo.clazz_user.subject = [[SubjectModel alloc] initWithDictionary:[[arrary objectAtIndex:0] valueForKeyPath:@"subject"] error:nil
            ];
            shareUserInfo.clazz_user.clazz.grade = [[GradeModel alloc] initWithDictionary:[[[arrary objectAtIndex:0] valueForKeyPath:@"clazz"] valueForKeyPath:@"grade"] error:nil];
            shareUserInfo.isLogin = YES;
            if (userType == 1) {
                shareUserInfo.isTeachLogin = YES;
            }else if(userType == 2)
                shareUserInfo.isTeachLogin = NO;
        }else{
            result = NO;
            shareUserInfo.isLogin = NO;
            shareUserInfo.isTeachLogin = NO;
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"登陆失败" message:[JSON valueForKeyPath:@"describe"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alertView show];
        }
        
        if (block) {
            block(result,nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        if (block) {
            block(NO,error);
        }
    }];
}

+ (NSURLSessionDataTask *)userLogout:(void (^)(BOOL result, NSError *))block{
    NSDictionary * dict = @{@"token":[DSFUserInfo shareUserInstance].token};
    return [[AFAppDotNetAPIClient httpSharedClient] POST:@"user/logout" parameters:dict success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSLog(@"%@",task.originalRequest);
        NSDictionary *response = [JSON valueForKeyPath:@"data"];
        long code = [[JSON valueForKeyPath:@"code"] integerValue];
        BOOL result;
        if (code == 10000) {
            result = YES;
            shareUserInfo.isLogin = NO;
            shareUserInfo.token = nil;
        }else{
            result = NO;
            shareUserInfo.isLogin = YES;
        }
        
        if (block) {
            block(result,nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        if (block) {
            block(NO,error);
        }
    }];
}
//--通过邀请码注册家长(针对已登录用户)
+ (NSURLSessionDataTask *)regist:(void (^)(BOOL result,NSError *error))block withToken:(NSString *)token andInvitationCode:(NSString *)invitationCode andRelation:(NSString *)relation
{
    NSDictionary * dict = @{@"token": token, @"invitationCode":invitationCode,@"relation":relation};
  
    return [[AFAppDotNetAPIClient httpSharedClient] POST:@"user/regist" parameters:dict success:^(NSURLSessionDataTask * __unused task, id JSON) {
//        NSLog(@"%@",task.originalRequest);
        NSDictionary *response = [JSON valueForKeyPath:@"data"];
        long code = [[JSON valueForKeyPath:@"code"] integerValue];
        BOOL result;
        if (code == 10000) {
            result = YES;
          
        }else{
            result = NO;
        }
        
        if (block) {
            block(result,nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        if (block) {
            block(NO,error);
        }
    }];

}

//--通过邀请码注册为家庭成员并登录(针对新用户)
+ (NSURLSessionDataTask *)registWithLogin:(void (^)(BOOL result,NSError *error))block withUsername:(NSString *)username andPassword:(NSString *)password andUserType:(NSInteger)userType andPushUserId:(NSString *)pushUserId andInvitationCode:(NSString *)invitationCode andRelation:(NSString *)relation icon:(NSString *)icon
{
    NSDictionary * dict = @{@"username": username, @"password":password,@"userType":@(userType),@"pushUserId":pushUserId,@"invitationCode":invitationCode,@"icon":icon,@"relation":relation};
 
    [DSFUserInfo shareUserInstance].isLogin = NO;
    return [[AFAppDotNetAPIClient httpSharedClient] POST:@"user/registWithLogin" parameters:dict success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSLog(@"%@",task.originalRequest);
        NSDictionary *response = [JSON valueForKeyPath:@"data"];
        long code = [[JSON valueForKeyPath:@"code"] integerValue];
        BOOL result;
        if (code == 10000) {
            result = YES;
            shareUserInfo.token = [response valueForKeyPath:@"token"];
            shareUserInfo.userId = [[response valueForKeyPath:@"id"] integerValue];
            shareUserInfo.phone = [response valueForKeyPath:@"phone"];
            shareUserInfo.sex = [[response valueForKeyPath:@"sex"] integerValue];
            shareUserInfo.icon = [response valueForKeyPath:@"icon"];
            shareUserInfo.last_login_time = [response valueForKeyPath:@"last_login_time"];
            NSArray *arrary = [response valueForKeyPath:@"clazz_users"];
            shareUserInfo.clazz_user = [[ClassUserMoedel alloc] initWithDictionary:[arrary objectAtIndex:0]  error:nil];
            shareUserInfo.clazz_user.clazz = [[ClassModel alloc] initWithDictionary:[[arrary objectAtIndex:0] valueForKeyPath:@"clazz"] error:nil];
            shareUserInfo.clazz_user.subject = [[SubjectModel alloc] initWithDictionary:[[arrary objectAtIndex:0] valueForKeyPath:@"subject"] error:nil
                                                ];
            shareUserInfo.clazz_user.clazz.grade = [[GradeModel alloc] initWithDictionary:[[[arrary objectAtIndex:0] valueForKeyPath:@"clazz"] valueForKeyPath:@"grade"] error:nil];
            shareUserInfo.isLogin = YES;
            if (userType == 1) {
                shareUserInfo.isTeachLogin = YES;
            }else if(userType == 2)
                shareUserInfo.isTeachLogin = NO;
        }else{
            result = NO;
            shareUserInfo.isLogin = NO;
            shareUserInfo.isTeachLogin = NO;
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"登陆失败" message:[JSON valueForKeyPath:@"describe"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alertView show];
        }
        
        if (block) {
            block(result,nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        if (block) {
            block(NO,error);
        }
    }];

}
+ (NSURLSessionDataTask *)getClazzUsers:(void (^)(BOOL result,NSArray *classUserArr,NSError *error))block withToken:(NSString *)token andClazzId:(int)clazzId{
    NSDictionary * dict = @{@"token":token,@"clazzId":@(clazzId)};
    return [[AFAppDotNetAPIClient httpSharedClient] POST:@"clazz/getClazzUsers" parameters:dict success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSLog(@"%@",task.originalRequest);
        NSArray *array = [JSON valueForKeyPath:@"data"];
        NSMutableArray *classArray = [[NSMutableArray alloc]initWithCapacity:0];
        long code = [[JSON valueForKeyPath:@"code"] integerValue];
        BOOL result;
        if (code == 10000) {
            result = YES;
            for (NSDictionary * dic in array) {
                OtherClassModel *model = [[OtherClassModel alloc]initWithDictionary:dic error:nil];
                [classArray addObject:model];
            }
        }else
            result = NO;
        
        if (block) {
            block(result,classArray,nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        if (block) {
            block(NO,nil,error);
        }
    }];
}

+ (NSURLSessionDataTask *)getMyFamilyMembers:(void (^)(BOOL result,NSString *failMessage,NSArray *familyMembers,NSError *error))block withToken:(NSString *)token andClazzId:(int)clazzId{
    NSDictionary * dict = @{@"token":token,@"clazzId":@(clazzId)};
    return [[AFAppDotNetAPIClient httpSharedClient] POST:@"user/getMyFamilyMembers" parameters:dict success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSLog(@"%@",task.originalRequest);
        NSString *message = nil;
        NSArray *array = [JSON valueForKeyPath:@"data"];
        NSMutableArray *classArray = [[NSMutableArray alloc]initWithCapacity:0];
        long code = [[JSON valueForKeyPath:@"code"] integerValue];
        BOOL result;
        if (code == 10000) {
            result = YES;
            for (NSDictionary * dic in array) {
                FamilyMember *model = [[FamilyMember alloc]initWithDictionary:dic error:nil];
                [classArray addObject:model];
            }
        }else{
            result = NO;
            message = [JSON valueForKeyPath:@"describe"];
        }
        if (block) {
            block(result,message,classArray,nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        if (block) {
            block(NO,nil,nil,error);
        }
    }];
}

+ (NSURLSessionDataTask *)getMyCollects:(void (^)(BOOL result,NSArray *classUserArr,NSError *error))block withPageNumber:(NSInteger)pageNumber withPageSize:(NSInteger)pageSize{
    NSDictionary * dict = @{@"token":[DSFUserInfo shareUserInstance].token,@"clazzId":@([DSFUserInfo shareUserInstance].clazz_user.clazz.id),@"pageNumber":@(pageNumber),@"pageSize":@(pageSize)};
    return [[AFAppDotNetAPIClient httpSharedClient] POST:@"user/getMyCollects" parameters:dict success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSLog(@"%@",task.originalRequest);
        NSString *message = nil;
        NSArray *array = [JSON valueForKeyPath:@"data"];
        NSMutableArray *classArray = [[NSMutableArray alloc]initWithCapacity:0];
        long code = [[JSON valueForKeyPath:@"code"] integerValue];
        BOOL result;
        if (code == 10000) {
            result = YES;
            for (NSDictionary * dic in array) {
                CollectModel *model = [[CollectModel alloc]initWithDictionary:dic error:nil];
                [classArray addObject:model];
            }
        }else{
            result = NO;
            message = [JSON valueForKeyPath:@"describe"];
        }
        if (block) {
            block(result,classArray,nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        if (block) {
            block(NO,nil,error);
        }
    }];

}

+ (NSURLSessionDataTask *)getMyInvitationCode:(void (^)(BOOL result,NSString *code,NSError *error))block{
    NSDictionary * dict = @{@"token":[DSFUserInfo shareUserInstance].token,@"clazzId":@([DSFUserInfo shareUserInstance].clazz_user.clazz.id)};
    return [[AFAppDotNetAPIClient httpSharedClient] POST:@"user/getMyInvitationCode" parameters:dict success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSLog(@"%@",task.originalRequest);
        NSString *message = nil;
        NSString *invitationCode = [JSON valueForKeyPath:@"describe"];
        long code = [[JSON valueForKeyPath:@"code"] integerValue];
        BOOL result;
        if (code == 10000) {
            result = YES;
        }else{
            result = NO;
            message = [JSON valueForKeyPath:@"describe"];
        }
        if (block) {
            block(result,invitationCode,nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        if (block) {
            block(NO,nil,error);
        }
    }];
}

@end

@implementation ClassModel

@end

@implementation ClassUserMoedel

@end

@implementation SubjectModel

@end

@implementation GradeModel
@synthesize description;
@end

@implementation OtherClassModel

@end

@implementation FamilyMember

@end

@implementation CollectModel

@end
